#!/usr/bin/env python

import sys

sys.path.insert(0, '../')

import os

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "meiduo_mall.settings")

import django

django.setup()

import os
from utils.goods import get_categories, get_breadcrumb, get_goods_specs
from django.http import JsonResponse
from meiduo_mall import settings
from goods.models import SKU


def generic_detail_html(sku_id):
    # try:
    #
    #     sku = SKU.objects.get(id=sku_id)
    # except Exception as e:
    #     return JsonResponse({'code': 400, 'errmsg': 'The sku_id not exist'})

    categories = get_categories()
    breadcrumb = get_breadcrumb(sku.category)

    context = {
        'categories': categories,
        'breadcrumb': breadcrumb,
        'sku': sku,
    }
    # 页面静态化：渲染
    # 1、加载渲染模板
    from django.template import loader
    # index_template = loader.get_template('index.html')
    index_template = loader.get_template('detail.html')
    # 2、把数据传给模板
    index_html_data = index_template.render(context)
    # 3、把渲染好的HTML，写入到指定文件
    # base_dir 的上一级
    file_path=os.path.join(os.path.dirname(settings.BASE_DIR), 'front_end_pc/goods/%s.html'%sku.id)

    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(index_html_data)

    print(sku.id)


skus = SKU.objects.all()
for sku in skus:
    generic_detail_html(sku)
